<template>
    <el-form label-width="110px" size="small" class="form-content" :key="renderCountKey">
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="产品代码:" v-if="isBatchStock">
                    <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                </el-form-item>
                <el-form-item label="组合编码:" v-if="isBatchStock">
                    <el-select
                        v-model="instruction.fundAccountCode"
                        size="mini"
                        @change="handleChange(instruction.fundAccountCode, 'fundAccountCode')"
                    >
                        <el-option
                            v-for="i in computedFundAccountCodeSelectData"
                            :key="i.fundAccountCode"
                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                            :value="i.fundAccountCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证券代码:" v-if="isBatchFund">
                    <el-select
                        v-model="instruction.stockCode"
                        @change="handleChange(instruction.stockCode, 'stockCode')"
                        filterable
                        clearable
                        :filter-method="getstockCodeList"
                        @visible-change="handleStockVisibleChange"
                        :loading="selectLoading"
                        size="mini"
                    >
                        <el-option
                            v-for="i in stockCodeSelectData"
                            :key="i.stockCode"
                            :label="i.stockCode + ' ' + i.stockNameSt"
                            :value="i.stockCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="业务类型:">
                    <el-select v-model="instruction.businClass" size="mini">
                        <el-option value="E" label="交易所大宗交易"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="委托方向:">
                    <el-select
                        v-model="instruction.orderDirection"
                        size="mini"
                        :class="['font-color-' + textColor]"
                        @change="handleChange(instruction.orderDirection, 'orderDirection')"
                    >
                        <el-option
                            v-for="i in orderDirectionSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :style="handleOptionColor(i.dictKey)"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <div v-if="isBatchFund">
                    <el-form-item label="价格模式:">
                        <el-select v-model="instruction.orderPriceType" size="mini" disabled>
                            <el-option value="1" label="1-限价"></el-option>
                            <el-option value="2" label="2-市价"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="当前市价:">
                        <el-input v-model="calcPrice" disabled :class="['font-color-' + textColor]">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                </div>
                <el-form-item label="交易对手:" v-if="isBatchStock">
                    <el-select
                        v-model="instruction.opponentCode"
                        @change="handleChange(instruction.opponentCode, 'opponentCode')"
                        filterable
                        clearable
                        :filter-method="getOpponentCode"
                        :loading="selectLoading"
                        size="mini"
                        @visible-change="handleOpponentVisibleChange"
                    >
                        <el-option v-for="i in opponentCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <div v-if="isBatchStock">
                    <el-form-item label="价格模式:">
                        <el-select v-model="instruction.orderPriceType" size="mini" disabled>
                            <el-option value="1" label="1-限价"></el-option>
                            <el-option value="2" label="2-市价"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="当前市价:">
                        <el-input v-model="calcPrice" disabled :class="['font-color-' + textColor]">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                </div>

                <el-form-item :label="orderPriceLabel">
                    <RiskInputNumber
                        :input="orderPrice"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="15"
                        :field="'orderPrice'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="指令数量:">
                    <RiskInputNumber
                        :inputAfter="orderAmountUnit[stockInfo && stockInfo.categoryCode]"
                        :input="instruction.orderAmount"
                        :maxlength="15"
                        :colorStyle="textColor"
                        :precision="2"
                        :field="'orderAmount'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item :label="orderBalanceLabel">
                    <el-tooltip
                        v-if="instruction.orderBalance && instruction.orderBalance != ''"
                        placement="top"
                        :enterable="false"
                        :content="computedorderBalanceChinese"
                    >
                        <RiskInputNumber
                            :disabled="true"
                            :input="instruction.orderBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :field="'orderBalance'"
                            :precision="2"
                            :maxlength="15"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-tooltip>
                    <RiskInputNumber
                        v-else
                        :disabled="true"
                        :input="instruction.orderBalance"
                        :field="'orderBalance'"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :maxlength="15"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="交易对手:" v-if="isBatchFund">
                    <el-select
                        v-model="instruction.opponentCode"
                        @change="handleChange(instruction.opponentCode, 'opponentCode')"
                        filterable
                        clearable
                        :filter-method="getOpponentCode"
                        :loading="selectLoading"
                        size="mini"
                        @visible-change="handleOpponentVisibleChange"
                    >
                        <el-option v-for="i in opponentCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import Invest from '@/common/dict/invest';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { getBusinessType } from '@/pages/risk-time/api';
import { handleTextColor, highlightColor, NumberToWords } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';

@Component({
    name: 'ExchangeBulkForm',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})
// 交易所大宗
export default class ExchangeBulkForm extends Vue {
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多证券指令
    @Prop()
    selectStockInfo: any;
    @Prop()
    detail: any;
    handleOptionColor = handleTextColor;
    // 指令数量单位
    orderAmountUnit = {
        JJ: '份',
        GP: '股',
        ZQ: '张',
    };

    // 风控指令表单
    instruction: any = {
        businClass: 'E', // 业务类型
        fundCode: '', // 产品序号
        fundAccountCode: '', // 组合编码
        orderUser: getUser().userCode,
        orderPurpose: '1', // 指令用途
        investType: '1', // 投资类型
        instructionType: '7',
        marketCode: '', // 市场序号
        reportCode: '', // 申报代码
        orderDirection: '', // 订单方向
        orderPriceType: '2', // 价格模式
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        orderLevel: '1', // 指令优先级
        // cancelType: '3',
        opponentCode: '', // 交易对手编码
        stockCode: '',
    };

    Invest: any = new Invest(); // 指令相关字典类
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    innerOrderDirectionData: any[] = [];
    orderDirectionData: any[] = [];
    allStockType: any[] = []; // 所有证券类别数据
    stockTypePojo: any = {};
    allOrderDirection: any[] = []; // 所有订单方向数据
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    currentAmount: string = ''; // 当前可用持仓
    orderPrice: string = '';
    orderPriceLabel: string = '净价价格:';
    orderBalanceLabel: string = '净价金额:';
    calcPrice: string = '';
    stockInfo: any = {};
    textColor: string = '';

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo) {
            // this.stockInfo = this.selectStockInfo;
            this.instruction.stockCode = this.selectStockInfo?.stockCode;
            this.instruction.reportCode = this.selectStockInfo?.reportCode;
            this.instruction.marketCode = this.selectStockInfo?.marketCode;
            if (this.selectStockInfo.marketCode && this.selectStockInfo.stockType) {
                this.handleStockBusinessType(this.selectStockInfo.marketCode, this.selectStockInfo.stockType, true);
            }
        }
    }

    @Watch('instruction.stockCode', { immediate: true, deep: true })
    getCalcPrice() {
        if (this.instruction.stockCode) {
            this.$axios.post('/dataEngine/getStockPrice/' + this.instruction.stockCode).then((result: any) => {
                this.calcPrice = result;
                this.calcPrice = result.toString();
            });
        } else {
            this.calcPrice = '';
        }
    }

    mounted() {
        this.getstockCodeList('');
        this.getOpponentCode('');
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            await this.getstockCodeList('');
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === instruction.stockCode);
            if (this.stockInfo && this.stockInfo.marketCode && this.stockInfo.stockType) {
                this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, false);
            }

            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.instruction.businClass = this.instruction.businessType;
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (['1', '3'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[1];
        } else if (['2', '4'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    /* ******************** 指令表单相关start ********************** */

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        if (field !== 'orderPrice') {
            this.instruction[field] = value.toString();
        }
        if (field === 'orderPrice') {
            this.orderPrice = value.toString();
            this.handlePriceChange(value);
        } else if (field === 'orderAmount') {
            this.calculateOrderBalance();
        }
        this.$emit('handleSettingValue', this.instruction, '');
    }

    // 参数变动
    handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'stockCode') {
            this.handleStockCode(value, true);
        } else if (field === 'opponentCode') {
            this.getOpponentCode(value);
        }
        this.$emit('handleSettingValue', this.instruction, '');
    }

    // 组合编码下拉框计算属性
    get computedFundAccountCodeSelectData() {
        return this.fundAccountCodeSelectData[this.instruction.fundCode] || [];
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (newData && newData.length) {
            this.instruction.fundAccountCode = newData[0].fundAccountCode;
        }
    }

    // 指令金额 大写中文
    get computedorderBalanceChinese() {
        return NumberToWords(this.instruction.orderBalance.toString());
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    // 获取证券持仓
    async getStockPosition() {
        await this.$axios
            .get('baseInfomation/stocks/' + this.instruction.fundCode + '/' + this.instruction.stockCode)
            .then((res: any) => {
                if (res && res.length) {
                    this.currentAmount = res[0].currentAmount;
                } else {
                    this.currentAmount = '0';
                }
            })
            .catch(() => {
                this.currentAmount = '0';
            });
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(e: string) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/stock/select/' + 1, {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }

    // 获取交易对手方数据
    getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    handleOpponentVisibleChange(val: any) {
        if (!val) {
            this.getOpponentCode('');
        }
    }

    // 获取指令金额 = 指令价格 * 指令数量
    handleOrderBalance() {
        this.instruction.orderBalance = (Number(this.instruction.orderPrice) * Number(this.instruction.orderAmount)).toFixed(2).toString();
    }

    handlePriceChange(value: string) {
        // 修改指令价格
        if (value) {
            // 根据输入值计算
            this.instruction.orderPriceType = '1';
        } else {
            this.instruction.orderPriceType = '2';
        }
        this.calculateOrderBalance();
    }

    // 计算指令金额
    calculateOrderBalance() {
        // 计算指令金额
        if (this.instruction.orderPriceType === '1') {
            this.instruction.orderBalance = (Number(this.orderPrice) * Number(this.instruction.orderAmount)).toFixed(2).toString();
            this.instruction.orderPrice = this.orderPrice;
        } else {
            this.instruction.orderBalance = (Number(this.calcPrice || 0) * Number(this.instruction.orderAmount || 0)).toFixed(2).toString();
            this.instruction.orderPrice = this.calcPrice.toString();
        }
    }

    // 证券代码选中事件 => 请求 证券信息 & 订单方向
    handleStockCode(value: string, reset: boolean) {
        try {
            this.stockCodeSelectData.forEach(item => {
                if (item.stockCode === value) {
                    if (item.categoryCode === 'JJ' || item.categoryCode === 'GP') {
                        this.orderBalanceLabel = '指令金额:';
                        this.orderPriceLabel = '指令价格:';
                        throw new Error(item.stockCode);
                    } else {
                        this.orderBalanceLabel = '净价金额:';
                        this.orderPriceLabel = '净价价格:';
                        throw new Error(item.stockCode);
                    }
                }
            });
        } catch (error) {}
        if (reset) {
            this.instruction.orderDirection = '';
            this.instruction.orderAmount = '';
            this.instruction.orderBalance = '';
            this.instruction.orderPrice = '';
            this.orderPrice = '';
            this.instruction.orderPriceType = '2';
        }
        if (value) {
            this.$axios('/baseInfomation/stockCode/' + value).then((res: any) => {
                if (res) {
                    if (res.foreverStock) {
                        this.instruction.investType = '3';
                    } else {
                        this.instruction.investType = '1';
                    }
                }
            });
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === value);
            this.$emit('getStockInfo', this.stockInfo);
            if (this.stockInfo && this.stockInfo.marketCode && this.stockInfo.stockType) {
                this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, reset);
            }
            let stockType = null;
            for (let i = 0; i < this.stockCodeSelectData.length; i++) {
                const ele = this.stockCodeSelectData[i];
                if (ele.stockCode === value) {
                    stockType = ele.stockType;
                    this.instruction.marketCode = ele.marketCode;
                    this.instruction.reportCode = ele.reportCode;
                    break;
                }
            }
        } else {
            this.orderDirectionSelectData = [];
        }
    }

    // 根据证券信息获取业务类型
    async handleStockBusinessType(marketCode, stockType, type) {
        let res = await getBusinessType(marketCode, stockType);
        if (res && res.length > 0) {
            this.innerOrderDirectionData = res;
            this.innerOrderDirectionData.filter(ele => {
                if (ele.dictKey == this.instruction.businClass) {
                    this.orderDirectionSelectData = JSON.parse(ele['innerDictionary'] || {});
                    if (this.orderDirectionSelectData.length && type) {
                        this.instruction.orderDirection = this.orderDirectionSelectData[0].dictKey;
                    }
                }
            });
        }
    }

    /* ******************** 指令表单相关end ********************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/order-form';
</style>
